<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\Controller;
use app\admin\model\RoleModel;
use app\admin\model\UserModel;
session_start();
class User extends Controller
{
    //用户列表
    public function index()
    {
        if(request()->isAjax()){

            $param = input('param.');

            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = [];
            if (!empty($param['searchText'])) {
                $where['user_name'] = ['ke', '%' . $param['searchText'] . '%'];
            }
            $user = new UserModel();
            $selectResult = $user->getUsersByWhere($where, $offset, $limit);

            $status = config('user_status');

            // 拼装参数
            foreach($selectResult as $key=>$vo){

                $selectResult[$key]['last_login_time'] = date('Y-m-d H:i:s', $vo['last_login_time']);
                $selectResult[$key]['status'] = $status[$vo['status']];
                if( @$_SESSION["think"]['id'] == $vo['id'] || 1 == $vo['id']){
                    $selectResult[$key]['operate'] = '';
                    continue;
                }
                $selectResult[$key]['operate'] = showOperate($this->makeButton($vo['id']));

            }

            $return['total'] = $user->getAllUsers($where);  //总数据
            $return['rows'] = $selectResult;

            return json($return);
        }

        return $this->fetch();
    }
    //用户列表
    public function salesman()
    {
        if(request()->isAjax()){

            $param = input('param.');

            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $userid = $_SESSION["think"]['id'];
            $whereor = [];
            $order = 'id desc';//管理员列表倒序
            $where['role_id'] = 3;//业务员id=3
            if ( $userid != 1) {
                $where['user_name'] = @$_SESSION["think"]['username'];
                $whereor['upid'] = $userid;
                $order = 'id asc';//业务员列表正序
            }

            


            if (!empty($param['searchText'])) {
                $where['user_name'] = ['like', '%' . $param['searchText'] . '%'];
            }

            $selectResult = db('user')->alias('su')
                    ->join('role sr','su.role_id = sr.id')
                    ->field('su.*,role_name')
                    ->where($where)
                    //->whereOr($whereor)
                    ->limit($offset, $limit)
                    ->order($order)
                    ->select();
                    //echo db('user')->getLastSql();
            
            //var_dump($subnum);die;
            
            $status = config('user_status');

                foreach($selectResult as $key=>$vo){
                    //读取订单表，每个业务员订单数，更新到用户表的提交表量
                    $subnum = null;
                    $subnum = db('order')->field('id')->where("state = 0 and salemanid={$vo['id']}")->count();
                    db('user')->where('id',$vo['id'])->update(['subnum'=>$subnum]);
                    //echo db('order')->getLastSql();
                
                    $selectResult[$key]['last_login_time'] = date('Y-m-d H:i:s', $vo['last_login_time']);
                    $selectResult[$key]['status'] = $status[$vo['status']];

                    if (1==$_SESSION["think"]['id']) {
                        $selectResult[$key]['operate'] = showOperate($this->makeButton($vo['id']));
                    }else{
                        if($userid == $vo['id']){//登录用户只能编辑自己
                            //var_dump(@$selectResult[$key]['operate']);//die;
                            $selectResult[$key]['operate'] = '<a href="/admin/user/salesmanedit/id/'.$userid.'.html"><button type="button" class="btn btn-primary btn-sm"><i class="fa fa-paste"></i> 编辑</button></a> <a href="/admin/user/userorders/id/'.$userid.'.html"><button type="button" class="btn btn- btn-sm"><i class="fa fa-paste"></i> 全部订单</button></a> <a href="/admin/user/get_qrcode/id/'.$userid.'.html"> <button type="button" class="btn btn-info btn-sm"><i class="fa fa-qrcode"></i> 二维码</button></a>';
                        continue;
                        }
                        $selectResult[$key]['operate'] = showOperate($this->makeButton1($vo['id']));
                    }
                   
         
                }

            $return['total'] = db('user')->where($where)->whereOr($whereor)->count();//总数据
            //echo db('user')->getLastSql();

            $return['rows'] = $selectResult;
            return json($return);
        }

        return $this->fetch();
    }
    //下线列表
    public function userlower()
    {   
        if(request()->isAjax()){
            $param = input('param.');
            //var_dump($param);die;
            $limit = @$param['pageSize'];
            $offset = @($param['pageNumber'] - 1) * $limit;
            //$userid = $_SESSION["think"]['id'];
            $where['upid'] = $param['ids'];
            $selectResult = db('user')->alias('su')
                    ->join('role sr','su.role_id = sr.id')
                    ->field('su.*,role_name')
                    ->where($where)
                    ->limit($offset, $limit)
                    ->order('id desc')
                    ->select();
                    $status = config('user_status');
            foreach($selectResult as $key=>$vo){
                
                    $selectResult[$key]['last_login_time'] = date('Y-m-d H:i:s', $vo['last_login_time']);
                    $selectResult[$key]['status'] = $status[$vo['status']];
                    if (1==$_SESSION["think"]['id']) {
                        $selectResult[$key]['operate'] = showOperate($this->makeButton($vo['id']));
                    }
            }

            $return['total'] = db('user')->whereOr($where)->count();//总数据
         
            //echo db('user')->getLastSql();
            //echo db('user')->getLastSql();
            $return['rows'] = $selectResult;

            return json($return);
        }
        $ids = input('param.id');
        $this->assign([
            //'role' => $role->getRole(),
            //'status' => config('user_status'),
            'ids' => $ids
            
        ]);
        return $this->fetch();
    }
    // 添加业务员
    public function salesmanAdd()
    {
        if(request()->isPost()){

            $param = input('post.');

            $param['password'] = md5($param['password']);
            $param['add_time'] = time();
            $param['upid'] = $_SESSION["think"]['id'];
            $param['role_id'] = 3;
            $re=db('user')->field('user_name')->where('user_name',$param['user_name'])->find();
            //var_dump($re);die;
            if ($re) {
                return msg(-1, '', "业务员已存在");
            }else{
                $result=db('user')->insert($param);
            }
            //$downid=db('user')->insertGetId($param);
            //if ($downid!=null) {
            //查出上级id的所有下级，追加新注册的上去
            //$down=db('snake_user')->where('id',$data['upid'])->find();
            //$downid = $downid.",".$down['downid'];
            //$result=db('user')->where('id',$id)->update(['downid' => $downid]);   
            //}

            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', $this->getError());
            }else{

                return msg(1, url('user/salesman'), '添加用户成功');
            }

            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }

        $role = new RoleModel();
        $this->assign([
            'id' => @$_SESSION["think"]['id'],
            'role' => $role->getRole(),
            'status' => config('user_status')
        ]);

        return $this->fetch();
    }
    // 添加用户
    public function userAdd()
    {
        if(request()->isPost()){

            $param = input('post.');

            $param['password'] = md5($param['password']);
            $param['add_time'] = time();
            $user = new UserModel();
            $flag = $user->insertUser($param);
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }

        $role = new RoleModel();
        $this->assign([
            'role' => $role->getRole(),
            'status' => config('user_status'),
            
        ]);

        return $this->fetch();
    }

    // 编辑用户
    public function userEdit()
    {
        $user = new UserModel();

        if(request()->isPost()){

            $param = input('post.');
            if(empty($param['password'])){
                unset($param['password']);
            }else{
                $param['password'] = md5($param['password']);
            }
            $flag = $user->editUser($param);

            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }

        $id = input('param.id');

        $role = new RoleModel();

        $this->assign([
            'user' => $user->getOneUser($id),
            'status' => config('user_status'),
            'role' => $role->getRole()
        ]);
        return $this->fetch();
    }

    // 编辑用户
    public function salesmanEdit()
    {
        $user = new UserModel();

        if(request()->isPost()){

            $param = input('post.');

            if(empty($param['password'])){
                unset($param['password']);
            }else{
                $param['password'] = md5($param['password']);
            }
            $flag = $user->editSalesman($param);

            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }

        $id = input('param.id');
        $role = new RoleModel();

        $this->assign([
            'user' => $user->getOneUser($id),
            'status' => config('user_status'),
            'role' => $role->getRole()
        ]);

        return $this->fetch();
    }

    // 删除用户
    public function userDel()
    {
        $id = input('param.id');

        $role = new UserModel();
        $flag = $role->delUser($id);
        return json(msg($flag['code'], $flag['data'], $flag['msg']));
    }

    // 删除业务员
    public function salesmanDel()
    {
        $id = input('param.id');
        $duser=db('user')->where('upid',$id)->select();
        foreach ($duser as $key => $value) {
            //修改删除用户的所有下级的上级id为1
            db('user')->where('id',$duser[$key]['id'])->update(['upid' => '1']);
        }

        $role = new UserModel();
        $flag = $role->delUser($id);


        return json(msg($flag['code'], $flag['data'], $flag['msg']));
    }
    
    //树形
    public function treeView()
    {
       return $this->fetch();
    }

    public function treeViewData()
    {

        // 方法一
        // $data = '[{"name":"test1","icon":"\/static\/admin\/images\/upUser.png","children":[{"name":"test1_1","icon":"\/static\/admin\/images\/user.png"}]}]';

        // echo $data;

        // 方法二
      //   $data = array(
      //       array('name'=>'test1','icon'=>'/static/admin/images/upUser.png',
      //           'children'=>array(
      //           array('name'=>'test1_1','icon'=>'/static/admin/images/user.png')

      //           )
      //       )
      //   );
        
      // echo json_encode($data);

        if(request()->isPost()){

            $param = input('post.');

            $userid = $_SESSION["think"]['id'];
            $where['role_id'] = 3;//业务员id=3
            $where['upid'] = $userid;
            if (@$param["id"]) {
                $where['upid'] = $param['id'];
            }

            $selectResult = db('user')->field('user_name,id,upid')->where($where)->select();
            $selectResults = db('user')->field('user_name,id,upid')->where('role_id=3')->select();
            //echo db('user')->getLastSql();

                foreach ($selectResult as $key => $value) {
                    $data[$key]['name']=$value['user_name'];
                    $data[$key]['id']=$value['id'];
                    $data[$key]['upid']=$value['upid'];
                    
                    foreach ($selectResults as $v) {
                        if( $data[$key]['id'] == $v['upid']){
                            $data[$key]['isParent']="true";
                            break;
                        }else{
                            $data[$key]['isParent']="false";
                        }   
                        
                    }

                }
                //$data = '[{"name":"test1","id":"1","isParent":"true"},{"name":"test2","id":"2","isParent":"false"}]';echo $data;
                echo json_encode($data);

            }

    }
    //获取二维码
    public function get_qrcode(){

        // 获取传过来 业务员id
        $id = input('param.id');
        $user = new UserModel();
        $token = $user->getToken();
        ob_end_clean();
        $data_string  = array( 'scene' => "$id",'page' => "pages/index/index");
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token";

        $result = $user->curl_post($url,$data_string);
        echo $result;
           

    }

    // 小程序用户信息
    public function wxUser(){
        $wxuser = db('wxuser');
        if(request()->isAjax()){
            $return = $wxuser -> select();

            if($return){
                foreach ($return as $k => $v) {
                    $return[$k]["addtime"] = date('Y-m-d H:i:s', $v['addtime']);
                }

                return json($return);
            }
        }else{
        // 渲染模板输出
        return $this->fetch('wxUser');
        }
    }
    // 删除用户信息
    public function wxUserRemove(){
        // 接受 json 字符串
        $requestDataJson = $GLOBALS['HTTP_RAW_POST_DATA'];
        
        // json 字符串反序列化成数组
        $requestData = json_decode($requestDataJson,true);

        $result = db('wxuser')->where('id')->delete($requestData["id"]);

        if($result){
            echo 1;
        }
    }

    // 业务员详情
    public function salesmanDetail(){
        $user = new UserModel();
        $id = input('param.id');
        $role = new RoleModel();

        $this->assign([
            'user' => $user->getOneUser($id),
            'status' => config('user_status'),
            'role' => $role->getRole()
        ]);
        return $this->fetch('salesmanDetail');
    }
    // 业务员订单列表
    public function userorders(){
        $user = new UserModel();
        $id = input('param.id');
        //var_dump($id);
        $role = new RoleModel();
        if(request()->isAjax()){
            $param = input('param.');
            //$id=input('');
            //var_dump($param);die;
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            //$userid = $_SESSION["think"]['id'];
            //$whereor = [];
            //$order = 'id desc';//管理员列表倒序
            //$where['role_id'] = 3;//业务员id=3
            /*if ( $userid != 1) {
                $where['user_name'] = @$_SESSION["think"]['username'];
                $whereor['upid'] = $userid;
                $order = 'id asc';//业务员列表正序
            }*/

            $orderList = db("order") ->where("state = 0 and salemanid ='{$param['ids']}'")->field('id,userName,mobile,age,userHousehold,time,order_sn,order_status,aptitude')->limit($offset, $limit)->order('aptitude ,id desc')->select();
//echo db('order')->getLastSql();
            foreach($orderList as $key=>$vo){
                    if($orderList[$key]['aptitude']=='0'){
                        $orderList[$key]['aptitude']='<p style="color:red;">未审核</p>';
                    }else if($orderList[$key]['aptitude']=='1'){
                        $orderList[$key]['aptitude']='<p style="color:green;" >有资格</p>';
                    }else if($orderList[$key]['aptitude']=='2'){
                        $orderList[$key]['aptitude']='<p style="color:black;" >不通过</p>';
                    }

                    if($orderList[$key]['order_status']=='0'){
                        $orderList[$key]['order_status']= '<p style="color:red;">未审核</p>';
                    }else if($orderList[$key]['order_status']=='1'){ 
                        $orderList[$key]['order_status']= '<p style="color:green;" >资质通过</p>';
                    }else if($orderList[$key]['order_status']=='2'){ 
                        $orderList[$key]['order_status']= '<p style="color:black;" >资质不通过</p>';
                    }else if($orderList[$key]['order_status']=='3'){ 
                        $orderList[$key]['order_status']= '<p style="color:green;" >已经挑选方案</p>';
                        $orderList[$key]['operate2']= '<button class="btn btn-info classifyRemove"  data-ClassfiyId="'.$orderList[$key]['id'].'" onClick="detailData2(this)" title="查看详情"><i class="fa fa-eye"></i></button>';
                    }else if($orderList[$key]['order_status']=='4'){ 
                        $orderList[$key]['order_status']= '<p style="color:green;" >生成完整方案表</p>';
                        $orderList[$key]['operate2']= '<button class="btn btn-info classifyRemove"  data-ClassfiyId="'.$orderList[$key]['id'].'" onClick="detailData2(this)" title="查看详情"><i class="fa fa-eye"></i></button>';
                    }else if($orderList[$key]['order_status']=='5'){ 
                        $orderList[$key]['order_status']= '<p style="color:green;" >签协议</p>';
                    }else if($orderList[$key]['order_status']=='6'){ 
                        $orderList[$key]['order_status']= '<p style="color:green;" >签约</p>';
                    }else if($orderList[$key]['order_status']=='7'){ 
                        $orderList[$key]['order_status']= '<p style="color:green;" >放款</p>';
                    }
                    $orderList[$key]['operate']= '<button class="btn btn-info classifyRemove"  data-ClassfiyId="'.$orderList[$key]['id'].'" onClick="detailData(this)" title="查看详情"><i class="fa fa-eye"></i></button>';
                    
                }


            $return['total'] = db("order") ->where("state = 0 and salemanid ='{$param['ids']}'")->field('id')->count();//总数据
            

            $return['rows'] = $orderList;
            return json($return);
        }/*else{
        // 渲染模板输出
        return $this->fetch();
        }*/
        $this->assign([
            'user' => $user->getOneUser($id),
            'status' => config('user_status'),
            'role' => $role->getRole()
        ]);
        return $this->fetch();
    }
    //生成方案表
    public function ajaxScme(){
            if(request() ->isAjax()){
            $id = input('post.order_sn');
           
            $order_arr = db('order') ->where('id',$id) ->find();
            $order_sn = $order_arr['order_sn'];

            // $sn_arr = input('post.');

            // $order_sn = $sn_arr['order_sn'];
            $scheme = db('scheme');
            $goods = db('goods');
            
            
            $group= $scheme ->where("order_id = '{$order_sn}' AND concentration = 0 ")->group('versions') ->select();

            $i = 1;

            foreach ($group as $key => $value) {

                    $arr = $scheme ->where("order_id = '{$order_sn}' AND concentration = 0 and versions = '{$value['versions']}' ") ->order('sort')->select();
                    $arrs= $scheme ->where("order_id = '{$order_sn}' AND concentration = 1 and versions = '{$value['versions']}' ")->order('sort')->select();
                    
                    $arrlist[$i] = $arr;
                    $i=$i+1;
                    if($arrs != null){

                    
                    $arrlist[$i] = $arrs;
                    
                    $i = $i+1;}
            }
            
            //var_dump($arrlist);die();
            // $arrlist['3'] = $arr;
            // $arrlist['3']['0']["name"] = '2222222222222';
            // $arrlist['3']['1']["name"] = '2222222222222';
            // $arrlist['3']['2']["name"] = '2222222222222';
            // $arrlist['4'] = $arrs;
            // $arrlist['4']['0']["name"] = '2222222222222';
            // // $arrs['1'] =$arr;
            // $arrs['2'] = $arr;
            // $arrs['2']['0']["order_id"] = '2222222222222';
            // $arrs['2']['1']["order_id"] = '2222222222222';
            // $arrs['2']['2']["order_id"] = '2222222222222';
            // $arrs['2']['3']["order_id"] = '2222222222222';
            
            
            return json($arrlist);
        }else{
            return $this->fetch('salesman_order');
        }
        
    }
    /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton($id)
    {
        return [
            '编辑' => [
                'auth' => 'user/useredit',
                'href' => url('user/userEdit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste'
            ],
            /*'下线' => [
                'auth' => 'user/userlower',
                'href' => url('user/userlower', ['id' => $id]),
                'btnStyle' => '',
                'icon' => 'fa fa-paste'
            ],*/
            '全部订单' => [
                'auth' => 'user/userorders',
                'href' => url('user/userorders', ['id' => $id]),
                'btnStyle' => '',
                'icon' => 'fa fa-paste'
            ],
            '二维码' => [
                'auth' => 'user/get_qrcode',
                'href' => url('user/get_qrcode', ['id' => $id]),
                'btnStyle' => 'info',
                'icon' => 'fa fa-qrcode'
            ],
            '删除' => [
                'auth' => 'user/userdel',
                'href' => "javascript:userDel(" .$id .")",
                'btnStyle' => 'danger',
                'icon' => 'fa fa-trash-o'
            ],
        ];
    }
    /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton1($id)
    {
        return [
            '编辑' => [
                'auth' => 'user/salesmanedit',
                'href' => url('user/salesmanEdit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste'
            ],
            '全部订单' => [
                'auth' => 'user/userorders',
                'href' => url('user/userorders', ['id' => $id]),
                'btnStyle' => '',
                'icon' => 'fa fa-paste'
            ],
            '二维码' => [
                'auth' => 'user/get_qrcode',
                'href' => url('user/get_qrcode', ['id' => $id]),
                'btnStyle' => 'info',
                'icon' => 'fa fa-qrcode'
            ],
            /*'下线' => [
                'auth' => 'user/userlower',
                'href' => url('user/userlower', ['id' => $id]),
                'btnStyle' => '',
                'icon' => 'fa fa-paste'
            ],*/

            '删除' => [
                'auth' => 'user/userdel',
                'href' => "javascript:userDel(" .$id .")",
                'btnStyle' => 'danger',
                'icon' => 'fa fa-trash-o'
            ],
        ];
    }
}
